package com.luo.demo.config;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import lombok.Data;
import org.springframework.stereotype.Component;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisShardInfo;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 应用全局配置信息
 *
 * @author xiangnan
 * @date 2018/1/25 17:04
 */
@Data
@Component
public class ApplicationConfig {

    @Resource
    private SharedJedisConfig sharedJedisConfig;

    private List<JedisShardInfo> jedisShardInfoList;

    private JedisPoolConfig poolConfig;

    /**
     * bean init == @PostConstruct
     */
    @PostConstruct
    private synchronized void init() {
        this.jedisShardInfoList = convert(checkHostPortFormat(sharedJedisConfig.getHostPortList()),
                sharedJedisConfig.getTimeout());

        // jedis pool配置
        JedisPoolConfig poolConfig = new JedisPoolConfig();
        poolConfig.setMaxIdle(10);
        poolConfig.setMinIdle(5);
        poolConfig.setMaxTotal(2);
        poolConfig.setMaxWaitMillis(3000);

        this.poolConfig = poolConfig;
    }

    private List<JedisShardInfo> convert(List<String> hostPortList, int timeout) {
        List<JedisShardInfo> jedisShardInfoList = new ArrayList<>();

        hostPortList.forEach(hostPort -> {
            String[] host = StrUtil.splitToArray(hostPort, ':');
            String[] port = StrUtil.splitToArray(host[1], '@');
            JedisShardInfo jedisInfo = new JedisShardInfo(host[0], Convert.toInt(port[0]), timeout);
            jedisInfo.setPassword(port[1]);

            jedisShardInfoList.add(jedisInfo);
        });

        return jedisShardInfoList;
    }

    private List<String> checkHostPortFormat(List<String> hostPortList) {
        hostPortList.forEach(hostPort -> {
            if (!StrUtil.contains(hostPort, ':') || !StrUtil.contains(hostPort, '@')) {
                throw new RuntimeException("redis config error. example [host:port@password]");
            }
        });

        return hostPortList;
    }

}
